package cn.goktech.controller;

import cn.goktech.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller

public class RespController {
    /*
     * 方式一：使用response响应字符串，需要处理乱码问题，方法的返回值是void
     *
     * */
    @RequestMapping("/resp1")
    public void respString(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("Hello你好");
    }

    /*
     * 方式二：@ResponseBody以json格式向前端发送数据，不会以视图的方式去找视图资源
     *
     * */
    @RequestMapping("/resp2")
    @ResponseBody
    public String respString2() {
        return "hello你好";
    }

    /*
     * 方式三：响应bean对象
     * @ResponseBody会采用默认的jackJson进行对数据的json格式化
     * 需要手动将jsckjson依赖导入项目
     *  <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.0</version>
        </dependency>

     *
     * */
    @RequestMapping("/resp3")
    @ResponseBody
    public User resBean3() {
        User user = new User(101, "波波", "宜宾");
        return user;
    }

    /*
     * 方式四：响应List
     *
     * */
    @RequestMapping("/resp4")
    @ResponseBody
    public List<User> resList() {
        List<User> users = new ArrayList<User>();
        for (int i = 1; i < 5; i++) {
            User user1 = new User(100 + i, "波波" + i, i % 2 == 0 ? "资阳" : "宜宾");
            users.add(user1);
        }
        return users;
    }
}
